import React, { useEffect, useRef, useState } from 'react';
import { NavBar } from 'antd-mobile'
import { useNavigate } from 'react-router-dom';

import useDrag from './Hooks/useDrag';
const Camera: React.FC = () => {
    const navigate = useNavigate()
    const back = () => {
        navigate(-1)
    }
    const cameraVideoRef = useRef<HTMLVideoElement | null>(null);
    const cameraCanvasRef = useRef<HTMLCanvasElement | null>(null);
    const [isImageSaved, setIsImageSaved] = useState(false); // 用于判断是否已保存图片



    // 添加打开和关闭摄像头的事件
    function successFunc(mediaStream: MediaStream) {
        const video = cameraVideoRef.current;
        if (video && 'srcObject' in video) {
            video.srcObject = mediaStream;
        }
        video!.onloadedmetadata = () => {
            video?.play();
        };
    }

    function errorFunc(err: Error) {
        console.log(err);
    }

    // 进入该页面直接启动摄像头
    // 定义获取用户媒体权限的函数
    useEffect(() => {
        const video = cameraVideoRef.current;
        if (video) {
            navigator.mediaDevices
                .getUserMedia({ video: true, audio: true })
                .then(successFunc)
                .catch(errorFunc);
        }
    }, []);


    // 关闭摄像头
    const closeMedia = () => {
        const video = cameraVideoRef.current;
        const stream = video?.srcObject as MediaStream;
        if (stream) {
            stream.getTracks().forEach((track) => {
                track.stop();
            });
        }
    };

    // 获取当前视频帧并转化为图片
    const getImg = () => {
        const video = cameraVideoRef.current;
        const canvas = cameraCanvasRef.current;
        if (!video || !canvas) return null;
        const ctx = canvas.getContext('2d');
        if (!ctx) return null;
        // 画出视频帧
        ctx.drawImage(video, 0, 0, video.videoWidth, video.videoHeight);

        // 获取图片的base64字符串
        const imgStr = canvas.toDataURL('image/png'); // 默认为 image/png
        return imgStr; // 返回base64编码的图片字符串
    };

    // 保存图片并隐藏视频
    const saveImg = () => {
        const imgData = getImg();
        if (!imgData) return; // 如果未获取到图片数据，退出函数     
        localStorage.setItem('savedImage', imgData); // 保存图片数据到localStorage
        // 网页保存图片
        const saveLink = document.createElement('a') as HTMLAnchorElement;
        saveLink.href = imgData; // 使用 imgData 作为图片的 href
        saveLink.download = 'image.png';
        const event = new MouseEvent('click', {
            bubbles: true,      // 事件是否可以冒泡
            cancelable: false,  // 事件是否可以被取消
            view: window,       // 事件的视图
            detail: 0,          // 鼠标点击的按键数
            screenX: 0,         // 鼠标点击的水平坐标
            screenY: 0,         // 鼠标点击的垂直坐标
            clientX: 0,         // 鼠标点击时的客户区水平坐标
            clientY: 0,         // 鼠标点击时的客户区垂直坐标
            ctrlKey: false,     // 是否按下 ctrl 键
            altKey: false,      // 是否按下 alt 键
            shiftKey: false,    // 是否按下 shift 键
            metaKey: false,     // 是否按下 meta 键
            button: 0,          // 鼠标按钮（0 表示左键）
            relatedTarget: null // 相关的目标元素
        });
        saveLink.dispatchEvent(event);
        // 设置已保存状态，隐藏视频
        setIsImageSaved(true);
        navigate('/home/fileUploader')
    };

    return (
        <>
            <NavBar onBack={back}> </NavBar>

            {/* 如果保存了图片，则隐藏视频显示画布 */}
            {!isImageSaved && (
                <video
                    id="video"
                    style={{
                        width: '30rem', height: '30rem',
                        objectFit: 'cover', borderRadius: '26rem',
                        border: '2px solid #000000',
                        marginLeft: '6rem',
                        marginTop: '10rem'
                    }}
                    ref={cameraVideoRef}
                ></video>
            )}
            <canvas
                id="canvas"
                width='450px'
                height={window.innerHeight}
                ref={cameraCanvasRef}
                style={{
                    display: isImageSaved ? 'block' : 'none',

                }}
            ></canvas>
            {/* <button onClick={closeMedia}>关闭摄像头</button> */}
            <button onClick={saveImg} style={{
                margin: '0 auto',
                display: 'block',
                width: '100px', borderRadius: '50px',
                height: '50px', marginTop: '20rem'
            }}> </button >




        </>
    );
};

export default Camera;
